const express = require('express'); // 框架
const multipart = require('connect-multiparty'); // 文件上传中间件
const fs = require('fs'); // 文件
const { v4: uuid } = require('uuid'); // UUID

const response = require('module/response'); // 响应

const serverConfig = require('config/server-config'); // 服务器配置
const fileService = require('service/file-service');

const router = express.Router(); // 路由
const multipartMiddleware = multipart(); // 文件上传中间件

const filePrefixPath = serverConfig.dirname + '/file/'; // 文件存放地址

/**
 * 上传文件
 */
router.post('/upload/:folder?', multipartMiddleware, (req, res, next) => {
  let folder = req.params.folder ? req.params.folder + '/' : ''; // 文件夹
  let pathTemp = req.files.file.path; // 中间件文件临时存放位置
  let filename = uuid() + '.' + pathTemp.split('.')[1]; // 文件目标位置
  fileService.uploadFile(folder, pathTemp, filename, (err, result) => {
    response(res, result, err);
  });
});

router.get('/download/:folder?/:name', (req, res, next) => {
  let folder = req.params.folder ? req.params.folder + '/' : ''; // 文件夹
  let path = filePrefixPath + folder + req.params.name;
  fs.exists(path, (exists) => {
    if (exists) {
      var size = fs.statSync(path).size;
      var f = fs.createReadStream(path);
      res.writeHead(200, {
        'Content-Type': 'application/force-download',
        'Content-Disposition': 'attachment;filename=' + req.params.name,
        'Content-Length': size
      });
      f.pipe(res);
    } else {
      response(res, null, null, 404);
    }
  })
});

/**
 * 获取文件-图片
 */
router.get('/getImg/:folder?/:name', (req, res, next) => {
  let folder = req.params.folder ? req.params.folder + '/' : ''; // 文件夹
  let path = filePrefixPath + folder + req.params.name;
  fs.exists(path, (exists) => {
    if (exists) {
      // 将图片文件返回给客户端
      res.sendFile(path);
    } else {
      response(res, null, null, 404);
    }
  })
});

/**
 * 获取文件-文件流 必须要post，get会导致乱码
 */
router.post('/getFile/:folder?/:name', (req, res, next) => {
  let folder = req.params.folder ? req.params.folder + '/' : ''; // 文件夹
  let path = filePrefixPath + folder + req.params.name;
  fs.exists(path, (exists) => {
    if (exists) {
      // 将Content-Disposition暴露给外部使前端能够获取
      res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition');
      // 设置文件名
      res.setHeader('Content-Disposition', 'attachment;filename=' + req.params.name);
      // 将文件返回给客户端
      res.sendFile(path);
    } else {
      response(res, null, null, 404);
    }
  })
});

module.exports = router;
